package utils;


import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Before;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DruidJDBCUtils {
    private static DataSource ds;

    @Before
    //初始化
    public void init(){

        try {
            //加载配置文件
            Properties druidPro = new Properties();
            druidPro.load(DruidJDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(druidPro);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void druidTest(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        /**
         * 添加数据
         */
        try{
            conn = getConnection();
            String sql = "insert into points values(?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,"000");
            pstmt.setString(2,"testDruid");
            pstmt.setInt(3,400);
            int count = pstmt.executeUpdate();
            System.out.println(count);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close(pstmt,conn);
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Statement stmt,Connection conn){
        close(null,stmt,conn);
    }

    public static void close(ResultSet set,Statement stmt, Connection conn){
        if(set!=null){
            try {
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn!=null){
            try {
                conn.close();//归还资源
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取连接池
     */
    public static DataSource getDataSource(){
        return ds;
    }
}
